package com.warom.sdg.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.DownloadListener;
import android.webkit.PermissionRequest;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.DrawableRes;

import com.warom.sdg.R;
import com.warom.sdg.callback.WebViewJsCallback;
import com.warom.sdg.util.LogUtils;
import com.warom.sdg.webview.jsinterface.WebViewJsInterface;
import com.warom.sdg.webview.jsinterface.WebViewJsUserManagerInterface;
import com.warom.sdg.webview.jsinterface.WebViewJsOperationLogInterface;

@SuppressLint("SetJavaScriptEnabled")
public class WebViewWrapper extends RelativeLayout {
    private static final String TAG = "WebViewWrapper";
    private WebView webView;
    private ImageView ivBack;
    private ProgressBar progressBar;
    private AudioManager audioManager;
    private String mUrl;
    
    // 新增接口对象
    private WebViewJsInterface jsInterface;
    private WebViewJsCallback callback;
    private WebViewJsUserManagerInterface userManagerJsInterface;
    private WebViewJsOperationLogInterface operationLogJsInterface;

    public WebViewWrapper(Context context) {
        this(context, null);
    }

    public WebViewWrapper(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WebViewWrapper(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 获取音频管理器
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        // 初始化JS接口
        jsInterface = new WebViewJsInterface(context,this);
        userManagerJsInterface = new WebViewJsUserManagerInterface(context);
        operationLogJsInterface = new WebViewJsOperationLogInterface(context, this);
        initView(context);
        initWebViewSettings();
        initListener();
        
        LogUtils.logOperation("WebView", "初始化", "WebViewWrapper组件初始化完成");
    }

    /**
     * 设置JS回调接口
     * @param callback 回调接口
     */
    public void setJsCallback(WebViewJsCallback callback) {
        this.callback = callback;
       // jsInterface.setCallback(callback);
       LogUtils.logOperation("WebView", "设置", "设置JS回调接口");
    }
    
    /**
     * 从Android调用JavaScript函数
     * @param functionName JavaScript函数名
     * @param params 参数（可选）
     */
    public void callJsFunction(String functionName, String... params) {
        if (webView == null) return;
        
        StringBuilder jsCode = new StringBuilder();
        jsCode.append("javascript:").append(functionName).append("(");
        
        for (int i = 0; i < params.length; i++) {
            if (i > 0) {
                jsCode.append(",");
            }
            jsCode.append("'").append(params[i].replace("'", "\\'")).append("'");
        }
        
        jsCode.append(")");
        
        final String finalJsCode = jsCode.toString();
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(finalJsCode, null);
        } else {
            webView.loadUrl(finalJsCode);
        }
        
        Log.d(TAG, "调用JS函数: " + finalJsCode);
        LogUtils.logOperation("WebView", "调用JS", "函数: " + functionName + ", 参数数量: " + params.length);
    }
    
    /**
     * 发送消息到JavaScript
     * @param message 消息内容
     */
    public void sendMessageToJs(String message) {
        LogUtils.logOperation("WebView", "发送消息", "消息长度: " + message.length() + " 字节");
        callJsFunction("receiveFromAndroid", message);
    }

    private void initView(Context context) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.include_webview, this);
        ivBack = (ImageView) view.findViewById(R.id.iv_back);
        webView = view.findViewById(R.id.webView);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        
        LogUtils.logOperation("WebView", "UI初始化", "WebView界面元素初始化完成");
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebViewSettings() {
        WebSettings settings = webView.getSettings();
        
        // 启用JavaScript
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        
        // 添加JavaScript接口
        webView.addJavascriptInterface(jsInterface, "Android");
        webView.addJavascriptInterface(userManagerJsInterface, "AndroidUser");
        LogUtils.logOperation("WebView", "设置", "添加JavaScript接口，名称: Android, AndroidUser");
        
        // 启用DOM存储API
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        
        // 禁用应用缓存
        if (Build.VERSION.SDK_INT < 33) {
            try {
                settings.setAppCacheEnabled(false);
                settings.setAppCachePath("");
            } catch (Exception e) {
                Log.e(TAG, "Error setting AppCache", e);
                LogUtils.logError("WebView", "设置AppCache失败", e);
            }
        }
        
        // 启用地理位置
        settings.setGeolocationEnabled(true);
        
        // 缩放设置
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        
        // 表单数据 - 禁用保存表单数据
        settings.setSaveFormData(false);
        
        // 视图设置
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        
        // 允许混合内容，解决部分HTTPS网页中HTTP资源无法加载的问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        
        // 允许访问文件
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        
        // 允许通过file url加载的JavaScript访问其他file urls
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
            settings.setAllowUniversalAccessFromFileURLs(true);
        }
        
        // 启用媒体播放功能 - 关键设置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            settings.setMediaPlaybackRequiresUserGesture(false);
        }
        
        // 设置缓存模式为不使用缓存，每次都从网络加载
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        
        // 设置默认编码
        settings.setDefaultTextEncodingName("UTF-8");
        
        // 启用调试
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        
        // 禁用硬件加速可以解决一些渲染问题
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        
        // 滚动条设置
        webView.setHorizontalScrollBarEnabled(false);
        webView.setScrollbarFadingEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        
        // 下载监听
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Log.e(TAG, "onDownloadStart ==" + url);
                LogUtils.logOperation("WebView", "下载文件", "URL: " + url + ", 类型: " + mimetype);
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                webView.getContext().startActivity(intent);
            }
        });
        
        // 确保音频模式设置正确
        setupAudioMode();
        
        LogUtils.logOperation("WebView", "设置", "WebView设置完成，已启用JavaScript和其他功能");
    }
    
    // 设置正确的音频模式
    private void setupAudioMode() {
        try {
            // 设置为通信模式，这对于麦克风访问很重要
            audioManager.setMode(AudioManager.MODE_NORMAL);
            
            // 确保麦克风没有被静音
            if (audioManager.isMicrophoneMute()) {
                audioManager.setMicrophoneMute(false);
            }
            
            Log.d(TAG, "Audio mode set to: " + audioManager.getMode());
            Log.d(TAG, "Microphone muted: " + audioManager.isMicrophoneMute());
        } catch (Exception e) {
            Log.e(TAG, "Error setting up audio mode", e);
        }
    }

    private void initListener() {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(VISIBLE);
                LogUtils.logOperation("WebView", "页面开始加载", "URL: " + url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(GONE);
                mUrl = url;
                Log.d(TAG, "页面加载完成: " + url);
                LogUtils.logOperation("WebView", "页面加载完成", "URL: " + url);
                
                // 注入一些辅助脚本来处理可能的错误
                injectErrorHandlingScript();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                // 获取错误信息
                String errorDescription = "未知错误";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    errorDescription = error.getDescription().toString();
                }
                
                // 获取失败的URL
                String failingUrl = "";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    failingUrl = request.getUrl().toString();
                }
                
                Log.e(TAG, "页面加载错误: " + failingUrl + " - " + errorDescription);
                LogUtils.logError("WebView", "页面加载错误: " + failingUrl, new Exception(errorDescription));
                
                // 如果是主页加载失败，显示错误页面
                if (failingUrl.equals(mUrl)) {
                    // 主资源加载失败，显示本地错误页面
                    injectErrorHandlingScript();
                    String errorHtml = "<html><body>" +
                            "<div style='text-align:center; padding-top:30%;'>" +
                            "<h2>页面加载失败</h2>" +
                            "<p>" + errorDescription + "</p>" +
                            "<button onclick='window.location.reload()'>重新加载</button>" +
                            "</div></body></html>";
                    webView.loadDataWithBaseURL(null, errorHtml, "text/html", "UTF-8", null);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                Log.e(TAG, "SSL证书错误: " + error.toString());
                LogUtils.logError("WebView", "SSL证书错误: " + error.toString(), null);
                
                // SSL证书错误，默认接受继续加载
                // 正式环境应该提示用户是否继续
                handler.proceed();
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                // 更新进度条
                if (newProgress < 100) {
                    progressBar.setProgress(newProgress);
                    progressBar.setVisibility(VISIBLE);
                } else {
                    progressBar.setVisibility(GONE);
                    LogUtils.logOperation("WebView", "页面加载进度", "100%完成");
                }
            }
            
            // 处理控制台消息，帮助调试
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d(TAG, "JS控制台: " + consoleMessage.message() + " (行 " + consoleMessage.lineNumber() + ")");
                if (consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR) {
                    LogUtils.logError("WebView", "JS错误: " + consoleMessage.message(), null);
                }
                return true;
            }
            
            // 处理权限请求 - 关键方法
            @Override
            public void onPermissionRequest(final PermissionRequest request) {
                Log.d(TAG, "WebView请求权限: " + request.toString());
                LogUtils.logOperation("WebView", "权限请求", "资源: " + request.getResources().toString());
                
                // 自动授予WebView请求的权限
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        request.grant(request.getResources());
                    }
                } catch (Exception e) {
                    Log.e(TAG, "授予权限失败", e);
                    LogUtils.logError("WebView", "授予权限失败", e);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        request.deny();
                    }
                }
                
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    return; // 低于5.0的设备不支持此方法
                }
                
                Log.d(TAG, "onPermissionRequest from origin: " + request.getOrigin().toString());
                
                // 打印所有请求的资源
                String[] resources = request.getResources();
                for (String resource : resources) {
                    Log.d(TAG, "Resource requested: " + resource);
                }
                
                try {
                    // 确保在主线程中处理
                    ((Activity) getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                // 确保音频模式正确
                                setupAudioMode();
                                
                                // 授予所有请求的权限
                                request.grant(request.getResources());
                                Log.d(TAG, "Permission granted for resources");
                                
                                // 显示提示
                                Toast.makeText(getContext(), "麦克风权限已授予网页", Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                Log.e(TAG, "Error in permission grant", e);
                                try {
                                    request.deny();
                                } catch (Exception ex) {
                                    Log.e(TAG, "Error denying permission", ex);
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    Log.e(TAG, "Error granting permission", e);
                    try {
                        request.deny();
                    } catch (Exception ex) {
                        Log.e(TAG, "Error denying permission", ex);
                    }
                }
            }

            private CustomViewCallback mCustomViewCallback;
            //  横屏时，显示视频的view
            private View mCustomView;

            // 点击全屏按钮时，调用的方法
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                super.onShowCustomView(view, callback);

                //如果view 已经存在，则隐藏
                if (mCustomView != null) {
                    callback.onCustomViewHidden();
                    return;
                }

                mCustomView = view;
                mCustomView.setVisibility(View.VISIBLE);
                mCustomViewCallback = callback;
                addView(mCustomView);
                bringToFront();
                //设置横屏
                ((Activity) getContext()).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }

            // 取消全屏调用的方法
            @Override
            public void onHideCustomView() {
                super.onHideCustomView();
                if (mCustomView == null) {
                    return;
                }
                mCustomView.setVisibility(View.GONE);
                removeView(mCustomView);
                mCustomView = null;
                try {
                    mCustomViewCallback.onCustomViewHidden();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ((Activity) getContext()).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        });
    }
    
    // 注入错误处理脚本
    private void injectErrorHandlingScript() {
        String script = "try {\n" +
                "  window.onerror = function(message, source, lineno, colno, error) {\n" +
                "    console.log('JS Error: ' + message + ' at ' + source + ':' + lineno);\n" +
                "    return true;\n" +
                "  };\n" +
                "  \n" +
                "  // 修复可能的getUserMedia问题\n" +
                "  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {\n" +
                "    const originalGetUserMedia = navigator.mediaDevices.getUserMedia;\n" +
                "    navigator.mediaDevices.getUserMedia = function(constraints) {\n" +
                "      console.log('getUserMedia called with constraints:', JSON.stringify(constraints));\n" +
                "      \n" +
                "      // 确保音频约束正确\n" +
                "      if (constraints && constraints.audio) {\n" +
                "        // 如果audio是布尔值，转换为对象以添加更多设置\n" +
                "        if (typeof constraints.audio === 'boolean') {\n" +
                "          constraints.audio = {\n" +
                "            echoCancellation: false,\n" +
                "            noiseSuppression: false,\n" +
                "            autoGainControl: false\n" +
                "          };\n" +
                "        } else if (typeof constraints.audio === 'object') {\n" +
                "          // 如果已经是对象，添加或修改设置\n" +
                "          constraints.audio.echoCancellation = false;\n" +
                "          constraints.audio.noiseSuppression = false;\n" +
                "          constraints.audio.autoGainControl = false;\n" +
                "        }\n" +
                "        console.log('Modified constraints:', JSON.stringify(constraints));\n" +
                "      }\n" +
                "      \n" +
                "      return originalGetUserMedia.call(this, constraints)\n" +
                "        .then(function(stream) {\n" +
                "          console.log('getUserMedia succeeded');\n" +
                "          return stream;\n" +
                "        })\n" +
                "        .catch(function(err) {\n" +
                "          console.log('getUserMedia error:', err.name, err.message);\n" +
                "          throw err;\n" +
                "        });\n" +
                "    };\n" +
                "  } else {\n" +
                "    console.log('getUserMedia not supported');\n" +
                "  }\n" +
                "} catch(e) {\n" +
                "  console.log('Error setting up error handlers:', e);\n" +
                "}";
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(script, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    Log.d(TAG, "Script injection result: " + value);
                }
            });
        } else {
            webView.loadUrl("javascript:" + script);
        }
    }

    /**
     * 加载URL
     * @param url URL地址
     */
    public void loadUrl(String url) {
        loadUrl(url, false);
    }

    /**
     * 加载URL，指定是否使用缓存
     * @param url URL地址
     * @param useCache 是否使用缓存
     */
    public void loadUrl(String url, boolean useCache) {
        if (webView != null) {
            // 设置缓存模式
            WebSettings settings = webView.getSettings();
            if (useCache) {
                settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Log.d(TAG, "使用缓存模式加载: " + url);
                LogUtils.logOperation("WebView", "加载URL", "使用缓存模式加载: " + url);
            } else {
                settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
                Log.d(TAG, "不使用缓存加载: " + url);
                LogUtils.logOperation("WebView", "加载URL", "无缓存模式加载: " + url);
            }
            
            mUrl = url;
            // 加载URL
            webView.loadUrl(url);
        } else {
            Log.e(TAG, "WebView未初始化");
            LogUtils.logError("WebView", "加载URL失败，WebView未初始化", null);
        }
    }
    
    /**
     * 设置缓存是否启用
     * @param enabled true表示启用缓存，false表示禁用缓存
     */
    public void setCacheEnabled(boolean enabled) {
        if (webView != null) {
            WebSettings settings = webView.getSettings();
            
            if (enabled) {
                // 启用缓存
                settings.setCacheMode(WebSettings.LOAD_DEFAULT);
                Log.d(TAG, "已启用WebView缓存，将优先使用缓存");
                
                // 启用应用缓存
                if (Build.VERSION.SDK_INT < 33) {
                    try {
                        String cachePath = webView.getContext().getCacheDir().getAbsolutePath();
                        settings.setAppCachePath(cachePath);
                        settings.setAppCacheEnabled(true);
                    } catch (Exception e) {
                        Log.e(TAG, "启用AppCache时出错", e);
                    }
                }
                
                // 启用DOM存储
                settings.setDomStorageEnabled(true);
                settings.setDatabaseEnabled(true);
            } else {
                // 禁用缓存
                settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
                Log.d(TAG, "已禁用WebView缓存，将始终从网络加载");
                
                // 禁用应用缓存
                if (Build.VERSION.SDK_INT < 33) {
                    try {
                        settings.setAppCacheEnabled(false);
                    } catch (Exception e) {
                        Log.e(TAG, "禁用AppCache时出错", e);
                    }
                }
            }
        }
    }
    
    /**
     * 刷新页面，可选择是否使用缓存
     * @param useCache true表示使用缓存，false表示不使用缓存
     */
    public void refreshPage(boolean useCache) {
        if (webView != null && mUrl != null && !mUrl.isEmpty()) {
            // 设置缓存模式
            setCacheEnabled(useCache);
            
            if (useCache) {
                // 使用缓存刷新
                webView.reload();
                Log.d(TAG, "使用缓存刷新页面: " + mUrl);
            } else {
                // 无缓存刷新，添加特殊头部
                java.util.Map<String, String> headers = new java.util.HashMap<>();
                headers.put("Cache-Control", "no-cache, no-store, must-revalidate");
                headers.put("Pragma", "no-cache");
                headers.put("Expires", "0");
                
                webView.loadUrl(mUrl, headers);
                Log.d(TAG, "无缓存刷新页面: " + mUrl);
            }
        }
    }
    
    /**
     * 强制刷新当前页面，不使用缓存
     */
    public void refreshPage() {
        // 默认不使用缓存刷新
        refreshPage(false);
    }
    
    /**
     * 加载HTML字符串内容
     */
    public void loadHtml(String htmlContent) {
        webView.loadDataWithBaseURL("file:///android_asset/", htmlContent, "text/html", "UTF-8", null);
    }
    
    /**
     * 加载HTML字符串内容（带baseUrl）
     */
    public void loadHtml(String htmlContent, String baseUrl) {
        webView.loadDataWithBaseURL(baseUrl, htmlContent, "text/html", "UTF-8", null);
    }

    public void setProgressDrawable(@DrawableRes int id) {
        progressBar.setProgressDrawable(progressBar.getContext().getResources().getDrawable(id));
    }

    /**
     * 获取WebView
     * @return WebView实例
     */
    public WebView getWebView() {
        return webView;
    }

    /**
     * 获取JavaScript接口
     * @return JavaScript接口
     */
    public WebViewJsInterface getJsInterface() {
        return jsInterface;
    }

    public ImageView getBackView() {
        return ivBack;
    }

    public String getUrl() {
        return mUrl;
    }

    public boolean goBack() {
        if (webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }

    public void onResume() {
        if (webView != null) {
            webView.onResume();
        }
    }

    public void onPause() {
        if (webView != null) {
            webView.onPause();
        }
    }

    public void onDestroy() {
        if (webView != null) {
            webView.destroy();
        }
    }

    /**
     * 评估JavaScript代码，执行JavaScript函数
     * @param jsCode JavaScript代码
     */
    public void evaluateJavascript(String jsCode) {
        evaluateJavascript(jsCode, null);
    }
    
    /**
     * 评估JavaScript代码，执行JavaScript函数，并获取返回值
     * @param jsCode JavaScript代码
     * @param resultCallback 结果回调
     */
    public void evaluateJavascript(String jsCode, ValueCallback<String> resultCallback) {
        if (webView == null) return;
        
        Log.d(TAG, "执行JS代码: " + jsCode);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(jsCode, resultCallback);
        } else {
            // 对于API 19以下的设备，使用loadUrl方式执行JavaScript
            // 注意：这种方式无法获取返回值
            webView.loadUrl(jsCode);
            if (resultCallback != null) {
                resultCallback.onReceiveValue(null);
            }
        }
    }
}